import os
from pathlib import Path
from typing import Optional, Tuple
from docx import Document
import openpyxl
from openpyxl.worksheet.worksheet import Worksheet


class ExcelToWordConverter:
    """Excel文档转Word文档的高可靠性转换器"""

    @staticmethod
    def convert(excel_path: str,
                word_path: str,
                open_result: bool = False) -> Tuple[bool, str]:
        """
        执行转换主流程

        Args:
            excel_path: 输入的Excel文件路径
            word_path: 输出的Word文件路径
            open_result: 是否自动打开结果文件
            precondition_input: 前置条件
        Returns:
            (成功状态, 描述信息)
        """
        # 前置校验
        if  (validation_result := ExcelToWordConverter._validate_input(excel_path)):
            return (False, validation_result)

        try:
            document = ExcelToWordConverter._create_document(excel_path)
            document.save(word_path)

            if open_result:
                ExcelToWordConverter._open_file(word_path)

            return (True, f"成功转换到 {word_path}")

        except PermissionError as e:
            return (False, f"文件访问被拒绝: {str(e)}")
        except Exception as e:
            return (False, f"转换过程中发生错误: {str(e)}")

    @staticmethod
    def _validate_input(excel_path: str) -> Optional[str]:
        """验证输入文件有效性"""
        if not Path(excel_path).exists():
            return f"文件不存在: {excel_path}"
        if Path(excel_path).suffix.lower() not in ('.xlsx', '.xlsm'):
            return "仅支持.xlsx/.xlsm格式文件"
        return None

    @staticmethod
    def _create_document(excel_path: str) -> Document:
        """创建包含所有工作表的Word文档"""
        doc = Document()
        workbook = openpyxl.load_workbook(excel_path)
        try:
            for sheet_name in workbook.sheetnames:
                ExcelToWordConverter._add_sheet_to_doc(workbook[sheet_name], doc)
        finally:
            workbook.close()  # 显式关闭工作簿
        return doc

    @staticmethod
    def _add_sheet_to_doc(sheet: Worksheet, doc: Document) -> None:
        """将单个工作表添加到Word文档"""
        doc.add_heading(sheet.title+"测试", level=1)
        table = doc.add_table(rows=sheet.max_row, cols=sheet.max_column, style='Table Grid')

        # 处理合并单元格
        for merge_range in sheet.merged_cells.ranges:
            table.cell(merge_range.min_row - 1, merge_range.min_col - 1).merge(
                table.cell(merge_range.max_row - 1, merge_range.max_col - 1))

        # 填充数据
        for row_idx, row in enumerate(sheet.iter_rows(values_only=True), start=0):
            for col_idx, value in enumerate(row, start=0):
                if value is not None:
                    table.cell(row_idx, col_idx).text = str(value)

        doc.add_page_break()

    @staticmethod
    def _open_file(file_path: str) -> None:
        """安全打开结果文件"""
        if os.name == 'nt':  # Windows系统
            os.startfile(file_path)
        else:  # Mac/Linux系统
            os.system(f'open "{file_path}"' if os.uname().sysname == 'Darwin'
                      else f'xdg-open "{file_path}"')


if __name__ == '__main__':
    ExcelToWordConverter.convert("C:\\Users\\luxiaoyan\\Desktop\\input.xlsx","C:\\Users\\luxiaoyan\\Desktop\\input.doc",True)